#include <dspSimulator/instruction/mvkh.h>

bool MVKH::checkCondition(std::shared_ptr<DspMachine> dspMachine) {
    if (isCompactInstruction) {
        return true;
    } else {
        return checkStandardCondition(dspMachine);
    }
}

void MVKH::loadInstIRIntoJit(llvm::LLVMContext *llvmContext, llvm::Module *module,
                             std::shared_ptr<llvm::IRBuilder<>> irBuilder) {
    llvm::FunctionType *funcType = llvm::FunctionType::get(irBuilder->getVoidTy(), false);

    // ---------------------------------MVKH (.unit) uscst16, sint ---------------------------------------------
    {
        llvm::Function *mvkh = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "MVKHKind1",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", mvkh);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);
        auto dstReg = irBuilder->CreateLoad(dstRegPtr);
        auto dstRegLo = irBuilder->CreateAnd(dstReg, irBuilder->getInt32(0x0000ffff));

        auto cst16 = getCstN(module, irBuilder, 16);
        auto cst16ZExt = irBuilder->CreateZExt(cst16, irBuilder->getInt32Ty());
        auto shl = irBuilder->CreateShl(cst16ZExt, irBuilder->getInt32(16));

        auto res = irBuilder->CreateOr(shl, dstRegLo);
        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }
}

std::shared_ptr<Instruction> MVKH::decode(std::shared_ptr<InstInfo> instInfo, u64 baseCycle) {
    std::shared_ptr<MVKH> mvkh;
    auto dspInstInfo = std::dynamic_pointer_cast<DspInstInfo>(instInfo);
    bool isStandardInst = dspInstInfo->isStandardInstruction();
    if (isStandardInst) {
        // Standard指令
        auto data = vectorToBitSet<32>(dspInstInfo->getBits());
        if (checkBits<5>(data, 2, 0b11010) && existStandardCondition(data)) {
            mvkh = std::make_shared<MVKH>(dspInstInfo->getAddress(), baseCycle);
            mvkh->creg_z = extractBits<4>(data, 28);
            mvkh->dst = extractBits<5>(data, 23).to_ulong();
            mvkh->cst = extractBits<16>(data, 7).to_ulong();
            mvkh->s = data[1];
            if (mvkh->s == 0) {
                mvkh->funcUnit = FuncUnit::S1;
            } else {
                mvkh->funcUnit = FuncUnit::S2;
            }
            mvkh->p = data[0];
            mvkh->instFormat = InstFormat::Kind1;
        }
    }
    return mvkh;
}

void MVKH::executeCustom(std::shared_ptr<TargetMachine> targetMachine, ExecutePhase executePhase) {

}

std::shared_ptr<DspInstruction> MVKH::clone() {
    return std::make_shared<MVKH>(*this);
}

std::string MVKH::toString() const {
    return getStandardConditionString() + " " + m_name + " " + FuncUnitName[static_cast<u32>(funcUnit)] + " " +
           dec2hex(cst << 16) + "," + getDstReg32Name();
}
